<script lang="ts" setup>
import type { newsFromType, getTableType } from "./type";
import { ref, reactive, onMounted } from "vue";
import request from "@/utils/request";
import editor from "@/components/editor/index.vue";
import upload from "@/utils/upload";
import Upload from "@/components/upload/index.vue";
import { useStore } from "vuex";
import { useRoute } from "vue-router";
import router from "@/router";
const route = useRoute();
const store = useStore();
const newsFormRef = ref();
const newsFrom = reactive<newsFromType>({
  username: "",
  title: "",
  content: "",
  times: "",
  isShow: "0",
  cover: "",
  file: null,
});

onMounted(() => {
  getTable();
});

const newsFormRules = reactive({
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  content: [{ required: true, message: "请输入内容", trigger: "blur" }],
  cover: [{ required: true, message: "请选择封面", trigger: "blur" }],
});

const getTable = async () => {
  const res = await request.get<any, getTableType>(`news/detail/${route.params.id}`);
  Object.assign(newsFrom, res.data);
};

const submitForm = () => {
  newsFormRef.value.validate(async (valid: any) => {
    if (valid) {
      const res = await upload("/news/list", newsFrom);
      if ((res.code = "200")) {
        // store.commit("changeUserInfo", res.data);
        router.back();
      }
    }
  });
};

const handleChange = (data: any) => {
  newsFrom.content = data;
};
const handleChangeCover = (file: any) => {
  newsFrom.cover = URL.createObjectURL(file);
  newsFrom.file = file;
};
const goBack = () => {
  router.back();
};
</script>
<template>
  <el-page-header @back="goBack">
    <template #content>
      <span class="text-large font-600 mr-3"> 编辑新闻 </span>
    </template>
  </el-page-header>
  <div class="divBox">
    <el-form
      ref="newsFormRef"
      style="width: 80%"
      :model="newsFrom"
      :rules="newsFormRules"
      label-width="120px"
      class="demo-ruleForm"
      status-icon
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="newsFrom.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <editor
          @event="handleChange"
          :content="newsFrom.content"
          v-if="newsFrom.content"
        />
      </el-form-item>
      <el-form-item label="封面" prop="cover">
        <Upload @change="handleChangeCover" :avatar="newsFrom.cover"></Upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm()">更新</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<style lang="scss" scoped>
.divBox {
  display: flex;
  height: calc(100% - 24px);

  justify-content: center;
  align-items: center;
  .el-form {
    width: 50%;
  }
}
</style>
